from flask import Flask, request
from flask import render_template
import dbHandle
import handleJson
import json
import Kmeans
import Regis

app = Flask(__name__)


@app.route('/')
def loadingPage():
    return render_template('loading.html')


@app.route('/freshData')
def freshPage():
    state = dbHandle.refresh()
    result = json.dumps({'res': state}, ensure_ascii=False)
    return result, {"Content-Type": "application/json"}


@app.route('/main')
def mainPage():
    return render_template('main.html')


@app.route('/test')
def testPage():
    return render_template('cale_pie.html')


# 获取中国当日信息
@app.route('/getChinaDay')
def china_today():
    return dbHandle.get_chinaday()


# 获取省份信息
@app.route('/getProvinceDay')
def province_today():
    return dbHandle.get_provinceday()


# 获取城市当日信息
@app.route('/getCityDay')
def city_today():
    pname = request.args.get('pname')  # 获取参数
    sign = 'cdata'  # 确定要获取的类型
    if pname == 'p':  # 初始化从前端传来的数据是‘p’
        sign = 'pdata'
    res_list = []
    city_data = dbHandle.get_cityday(pname)
    temp = json.loads(city_data[0])[sign]
    for key in temp:
        res_list.append(handleJson.split_json(temp[key], key))
    res = json.dumps({'res': res_list}, ensure_ascii=False)  # 使用dumps转换时，‘ensure_ascii=False’可防止中文乱码
    return res, {"Content-Type": "application/json"}  # dumps返回的结果默认为‘text/html’格式，需要返回一个‘content-Type’header属性


# 获取国家每日新增信息
@app.route('/getchinaAddHistory')
def chinaAddHistory():
    addC_data = dbHandle.getAddHistory()
    addC_rs = json.dumps({'res': addC_data}, ensure_ascii=False)
    return addC_rs, {"Content-Type": "application/json"}


# 获取精准推送城市信息
@app.route('/city')
def OneCity():
    pname = request.args.get('pname')  # 获取参数
    cname = request.args.get('cname')  # 获取参数
    city_res = dbHandle.get_onecityday(pname, cname)
    return city_res


# 获取历史累计数据
@app.route('/getHistoryData')
def getHistoryData():
    return dbHandle.getDayHistory()


# 后台处理聚类信息，并获取结果
@app.route('/getClusterData')
def getClusterData():
    Cluster_res = Kmeans.Kmeans_Province()
    return Cluster_res


# 后台进行确诊新增数据预测，并获取结果
@app.route('/getPredictData')
def getPredictData():
    predict_res = Regis.get_predict_data()
    return predict_res


if __name__ == '__main__':
    app.run(debug=True)
